package com.yl.nettylearning.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author yangl
 */
public class FileChannelCopyDemo {
    /**
     * 用一个文件完成一个文件的拷贝
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{
        FileInputStream fileInputStream = new FileInputStream("test.txt");
        FileChannel fileInputChannel = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("test02.txt");
        FileChannel fileOutputChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true){
            //将buffer清空，重置标识位
            byteBuffer.clear();
            int read = fileInputChannel.read(byteBuffer);
            if(read == -1){
                //读完
                break;
            }
            //将buffer中的数据写入到fileOutChannel
            byteBuffer.flip();
            fileOutputChannel.write(byteBuffer);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}
